package com.dunshan.szg.config;

import brave.Tracer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * @author dunshan
 * @program: dunshan-pef
 * @description: 网关过滤
 * @date 2021-10-02 14:18:33
 */
@Component
public class globalTagFilter implements GlobalFilter {

    private final static Logger logger = LoggerFactory.getLogger(globalTagFilter.class);


    private Tracer tracer;

    @Autowired
    public void setTracer(Tracer tracer) {
        this.tracer = tracer;
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String dunshan = exchange.getRequest().getHeaders().getFirst("dunshan");
        if (dunshan != null) {
            logger.info("dunshan：" + dunshan);
            tracer.currentSpan().tag("dunshan", dunshan);
//            UUID uuid = UUID.randomUUID();
//            tracer.currentSpan().tag("traceId", uuid + "");
//            MDC.put("dunshan", "shadow");
            logger.info("压测流量：" + dunshan);
            ServerHttpRequest request = exchange.getRequest().mutate().header("dunshan", dunshan).build();
            exchange = exchange.mutate().request(request).build();
            return chain.filter(exchange);
        } else {
//            MDC.put("dunshan", "produce");
            logger.info("正常流量：" + dunshan);
        }

        return chain.filter(exchange);
    }
}
